import config from './config'
import type { ParamsInterface } from '@/constrain/interface'
class Service {
	private api(params : ParamsInterface) {
		return new Promise((resovle, reject) => {

			// 发送请求前提示一下
			uni.showLoading({
				title: '正在加载中...'
			})
			const { url, data, method } = params
			type HeaderType = {
				'Content-Type' : string,
				token ?: string
			}
			const header : HeaderType = {
				'Content-Type': 'application/json'
			}
			const token = uni.getStorageSync("token")
			token && (header.token = token)
			uni.request({
				url: config.BASEURL + url,
				data,
				method,
				header,
				success: res => {
					resovle(res.data)
				},
				fail: error => {
					reject(error)
				},
				// 不管成功失败都会走complate
				complete: () => {
					// 隐藏提示
					uni.hideLoading()
				}
			})
		})
	}

	get(params : ParamsInterface) {
		params.method = 'GET'
		return this.api(params)
	}
	post(params : ParamsInterface) {
		params.method = 'POST'
		return this.api(params)
	}
	put(params : ParamsInterface) {
		params.method = 'PUT'
		return this.api(params)
	}
	delete(params : ParamsInterface) {
		params.method = 'DELETE'
		return this.api(params)
	}
}
export default Service